package com.example.databasepj.service;

import com.example.databasepj.dto.*;
import com.example.databasepj.entity.AdminEntity;
import com.example.databasepj.entity.MerchantEntity;
import com.example.databasepj.entity.UserEntity;
import com.example.databasepj.exception.BusinessException;
import com.example.databasepj.exception.ErrorCode;
import com.example.databasepj.mapper.AdminMapper;
import com.example.databasepj.mapper.MerchantMapper;
import com.example.databasepj.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private MerchantMapper merchantMapper;

    public LoginResponse Login(int id, String password,String role){
        //管理员登陆
        if (role.equalsIgnoreCase("admin")){
            AdminEntity adminEntity = adminMapper.selectAdminById(id);
            if (adminEntity != null && adminEntity.getPassword().equals(password)){
                LoginData adminLoginData = new LoginData(adminEntity.getAdminId(),"管理员");
                return new AdminLoginResponse(true,adminLoginData);
            }
            else {
                //throw new BusinessException(ErrorCode.INVALID_CREDENTIALS);
                return new AdminLoginResponse(false,null);

            }

        }
        //用户登录
        else if(role.equalsIgnoreCase("user")){
            UserEntity user = userMapper.selectUserById(id);
            if(user!=null && user.getPassword().equals(password)){
                LoginData userData = new LoginData(user.getUser_id(),user.getUser_name());
                return new UserLoginResponse(true,userData);//按照json格式返回
            }
            else {
                return new UserLoginResponse(false,null);
            }

        }//商家登录
        else if(role.equalsIgnoreCase("merchant")){
            MerchantEntity merchantEntity = merchantMapper.selectMerchantById(id);
            if(merchantEntity!=null && merchantEntity.getPassword().equals(password)){
                LoginData merchantLoginData = new LoginData(id, merchantEntity.getMerchant_name());
                return new MerchantLoginResponse(true,merchantLoginData);
            }
            else {
                return new MerchantLoginResponse(false,null);
            }
        }
        else {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);

        }
        //return null;
    }




}
